﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Configuration;
using System.Xml;

using Spider.Ex;
using Spider.Entity;

namespace Spider
{
    public class ConfigManager
    {
        public Dictionary<SiteConfig, List<UriConfig>> GetUriConfig()
        {
            var result = new Dictionary<SiteConfig, List<UriConfig>>();

            XmlDocument xml = new XmlDocument();
            xml.Load("Config.xml");

            XmlNodeList webSites = xml.GetElementsByTagName("WebSite");

            foreach (XmlNode site in webSites)
            {
                if (site.Attributes["Action"].Value.TryBoolean() == false) continue;

                SiteConfig siteConfig = new SiteConfig();

                List<UriConfig> list = new List<UriConfig>();
                foreach (XmlNode uri in site.ChildNodes)
                {
                    if (uri.Attributes == null || uri.Attributes["Action"].Value.TryBoolean() == false)
                        continue;

                    UriConfig config = new UriConfig();
                    config.Uri = uri.Attributes["Uri"].Value;
                    config.City = uri.Attributes["City"].Value;
                    config.PageUri = uri.Attributes["PageUri"].Value;
                    config.PageIndex = uri.Attributes["PageIndex"].Value.TryInt();
                    config.PageCount = uri.Attributes["PageCount"].Value.TryInt();
                    config.ThreadCount = uri.Attributes["ThreadCount"].Value.TryInt();
                    config.Rule = uri.FirstChild.Attributes["Reg"].Value;
                    config.Parser = uri.Attributes["Parser"].Value;
                    list.Add(config);
                }

                siteConfig.SiteName = site.Attributes["SiteName"].Value;
                siteConfig.Spider = site.Attributes["Spider"].Value;

                result.Add(siteConfig, list);
            }
            return result;
        }

        public Dictionary<string, ParserConfig> GetParserConfig()
        {
            var result = new Dictionary<string, ParserConfig>();

            XmlDocument xml = new XmlDocument();
            xml.Load("Config.xml");

            XmlNodeList parsers = xml.GetElementsByTagName("HtmlParser")[0].ChildNodes;

            foreach (XmlNode item in parsers)
            {
                if (item.Attributes == null || item.Attributes["Action"].Value.TryBoolean() == false)
                    continue;

                ParserConfig config = new ParserConfig();
                config.Name = item.Attributes["Name"].Value;
                config.Parser = item.Attributes["Parser"].Value;
                result.Add(config.Name, config);
            }
            return result;
        }


    }
}
